# This file is managed by gitlab-ctl. Manual changes will be
# erased! To change the contents below, edit /etc/gitlab/gitlab.rb
# and run `sudo gitlab-ctl reconfigure`.


# What ports/sockets to listen on, and what options for them.
<%- @listen.each do |port, options| %>
listen "<%= port %>", <%= options %>
<%- end %>

<%- if @working_directory %>
working_directory '<%= @working_directory %>'
<%- end %>

# What the timeout for killing busy workers is, in seconds
timeout <%= @worker_timeout %>

# Whether the app should be pre-loaded
preload_app <%= @preload_app %>

# How many worker processes
worker_processes <%= @worker_processes %>

# Load the Gitlab::Cluster::LifecycleEvents module
# to notify the application of unicorn events
require_relative "<%= @install_dir %>/embedded/service/gitlab-rails/lib/gitlab/cluster/lifecycle_events"
require_relative "<%= @install_dir %>/embedded/service/gitlab-rails/lib/gitlab/log_timestamp_formatter.rb"

before_exec do |server|
  Gitlab::Cluster::LifecycleEvents.do_before_master_restart
end

run_once = true

before_fork do |server, worker|
  if run_once
    # There is a difference between Puma and Unicorn:
    # - Puma calls before_fork once when booting up master process
    # - Unicorn runs before_fork whenever new work is spawned
    # To unify this behavior we call before_fork only once (we use
    # this callback for deleting Prometheus files so for our purposes
    # it makes sense to align behavior with Puma)
    run_once = false

    # Signal application hooks that we're about to fork
    Gitlab::Cluster::LifecycleEvents.do_before_fork
  end

  old_pid = "#{server.config[:pid]}.oldbin"
  if old_pid != server.pid
    begin
      sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
      Process.kill(sig, File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
    end
  end
end

after_fork do |server, worker|
  Gitlab::Cluster::LifecycleEvents.do_worker_start
end

<%- if @pid %>
# Where to drop a pidfile
pid '<%= @pid %>'

<%- end %>
<%- if @stderr_path %>
# Where stderr gets logged
stderr_path '<%= @stderr_path %>'

<%- end %>
<%- if @stdout_path %>
# Where stdout gets logged
stdout_path '<%= @stdout_path %>'

<%- end %>
<%- if @worker_memory_limit_min %>
# Min memory size (RSS) per worker
ENV['GITLAB_UNICORN_MEMORY_MIN'] = (<%= @worker_memory_limit_min %>).to_s

<%- end %>
<%- if @worker_memory_limit_max %>
# Max memory size (RSS) per worker
ENV['GITLAB_UNICORN_MEMORY_MAX'] = (<%= @worker_memory_limit_max %>).to_s

<%- end %>

# Configure the default logger to use a custom formatter that formats the
# timestamps to be in UTC and in ISO8601.3 format
Configurator::DEFAULTS[:logger].formatter = Gitlab::LogTimestampFormatter.new
